<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Promise 详解</title>
</head>
<body>
    <script>
        //极简的实现
        //极简的实现+链式调用+延迟机制+状态
        class mPromise {
            callbacks = [];
            state = 'pending';//增加状态
            value = null;//保存结果
            constructor(fn) {
                fn(this._resolve.bind(this));
            }
            then(onFulfilled) {
                return new mPromise(resolve=>{
                    this._handle({
                        onFulfilled: onFulfilled || null,
                        resolve: resolve
                    });
                })
            }

            _handle(callback) {
                // debugger
                if (this.state === 'pending') {
                    this.callbacks.push(callback);
                    return;
                }
                //如果then中没有传递任何东西
                if (!callback.onFulfilled) {
                    callback.resolve(this.value);
                    return;
                }
                var ret = callback.onFulfilled(this.value);
                callback.resolve(ret);
            }

            _resolve(value) {
                // debugger
                this.state = 'fulfilled';//改变状态
                this.value = value;//保存结果
                this.callbacks.length != 0 && console.log(this.callbacks,'/this.callbacks')
                this.callbacks.forEach(callback => this._handle(callback));
            }
        }

        //Promise应用
        let p = new mPromise(resolve => {
            setTimeout(() => {
                console.log('done');
                debugger
                resolve('5秒');
            }, 500);
        }).then((tip) => {
            var g = new mPromise(resolve => {
                setTimeout(()=>{
                    console.log(tip,'第一个链子');
                    console.log('pone')
                    debugger
                    resolve('两秒')
                },200)
            })
            return g
        }).then(val=>{
            console.log(val,'第二个链子')
        })





        // console.log('《---------分割----------》')
        // let wp = new Promise(resolve => {
        //     setTimeout(() => {
        //         console.log('done');
        //         resolve('5秒');
        //     }, 5000);
        // }).then((tip) => {
        //     console.log(3333333)
        //     console.log(tip,'第一个链子');
        // }).then(val=>{
        //     console.log(val,'第二个链子')
        // })
        // console.log('《---------分割----------》')




    </script>
</body>
</html>